/*
 * File:   UserDelay.c
 * Author: Honrun
 */
#include "CH58x_common.h"
#include "stdint.h"

#include "DevicesTime.h"
#include "DevicesTimer.h"
#include "DevicesDelay.h"

/*
 * Return:      void
 * Parameters:  void
 * Description: DWT初始化
 */
void vSysTickDelayInit(void)
{
    /* DISABLE */
    SysTick->CTLR = 0;
    /* Clear state */
    SysTick->SR = 0;
    /* Load the SysTick Counter Value */
    SysTick->CNT = 0;
    /* Set the SysTick Counter Load */
    SysTick->CMP = 0xFFFFFFFFUL;
    /* ENABLE */
    SysTick->CTLR = SysTick_CTLR_STE_Msk | SysTick_CTLR_STCLK_Msk;
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 秒延时
 */
void vSysTickDelayS(float fTime)
{
    vSysTickDelayUs(fTime * 1000000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 毫秒延时
 */
void vSysTickDelayMs(float fTime)
{
    int32_t iTime = fTime;

    fTime -= iTime;

    while((iTime--) > 0)
    {
        vSysTickDelayUs(1000.0f);
    }

    vSysTickDelayUs(fTime * 1000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 微秒延时
 */
void vSysTickDelayUs(float fTime)
{
    uint32_t uiTimeStop = SysTick->CNT + (uint64_t)(fTime * (78000000 / 1000000));

    if(fTime < 0.0f)
        return;

    while(SysTick->CNT < uiTimeStop);
}

/*
 * Return:      void
 * Parameters:  void
 * Description: DWT初始化
 */
void vTimerDelayInit(void)
{
    cTimer3Init();
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 秒延时
 */
void vTimerDelayS(float fTime)
{
    vTimerDelayUs(fTime * 1000000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 毫秒延时
 */
void vTimerDelayMs(float fTime)
{
    vTimerDelayUs(fTime * 1000.0f);
}

/*
 * Return:      void
 * Parameters:  Time: 延时时间
 * Description: 微秒延时
 */
void vTimerDelayUs(float fTime)
{
    uint64_t ulTimeStop = lTimebaseGet() + (int64_t)fTime;

    while(lTimebaseGet() < ulTimeStop);
}
